from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import datetime, os, sys

#START: ChatMessage
class ChatMessage(db.Model):
	user = db.StringProperty(required = True)
	message = db.TextProperty(required = True)
	timestamp = db.DateTimeProperty(auto_now_add = True)
	chat = db.StringProperty(required = True)
CHATS = ['main', 'book', 'webdev']
#END: ChatMessage

class ChatRoomPoster(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		msg_text = self.request.get("message")
		chat = self.request.get("chat")
		msg = ChatMessage(user = user.nickname(), message = msg_text, chat = chat)
		msg.put()
		self.redirect('/enterchat?chat=%s' % chat)

class GenericChatPage(webapp.RequestHandler):
	def get(self):
		requested_chat = self.request.get("chat", default_value=None)
		if requested_chat is None or requested_chat not in CHATS:
			template_params = {
				"title": "Error, Requested chat not found",
				"chatname": requested_chat,
				"chats": CHATS
			}
			error_template = os.path.join(os.path.dirname(__file__), 'error.html')
			page = template.render(error_template, template_params)
			self.response.out.write(page)
		else:
			messages = db.GqlQuery("SELECT * FROM ChatMessage WHERE chat = :1 "
									"ORDER BY timestamp", requested_chat)
			template_params = {
				"title": "Peace's ChatRoom_Deneric",
				"msg_list": messages,
				"chat": requested_chat,
				"chats": CHATS
				}
			path = os.path.join(os.path.dirname(__file__),"multichat.html")
			page = template.render(path, template_params)
			self.response.out.write(page)
#START: ChatRoomCount
class ChatRoomCountedHandler(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		if user is None:
			self.redirect(users.create_login_url(self.request.uri))
		else:
			self.response.headers["Content-Type"] = "text/html"
			messages = db.GqlQuery("SELECT * FROM ChatMessage ORDER BY timestamp"
								"DESC LIMIT 20")
			msglist = messages.fetch()
			for msg in msglist:
				msg.deltatime = datetime.datetime.now() - msg.timestamp
			template_values = {
				'title': "Peace's ChatRoom",
				"msg_list": messages.fetch()
				}
			path = os.path.join(os.path.dirname(__file__), 'count.html')
			page = template.render(path, template_values)
			self.response.out.write(page)
#END: ChatRoomCountedHandler

#START: LandingPage
class ChatRoomLandingPage(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		if user is None:
			self.redirect(users.create_login_url(self.request.uri))
		else:
			self.response.headers["Content-Type"] = "text/html"
			messages = db.GqlQuery("SELECT * FROM ChatMessage ORDER BY timestamp"
									"DESC LIMIT 20")
			template_values = {
				'title': "Peace's ChatRoom_Landing",
				'msg_list': messages,
				'chat': CHATS
				}
			path = os.path.join(os.path.dirname(__file__), 'landing.html')
			page = template.render(path, template_values)
			self.response.out.write(page)
# END: LandingPage
chatapp = webapp.WSGIApplication([('/', ChatRoomLandingPage), \
								('/talk', ChatRoomPoster), \
								('/enterchat', GenericChatPage)])

def main():
	run_wsgi_app(chatapp)

if __name__ == "__main__":
	main()